package com.szcport.file;

import com.lowagie.text.DocumentException;
import com.lowagie.text.pdf.BaseFont;
import freemarker.template.Template;
import freemarker.template.TemplateException;
import lombok.extern.slf4j.Slf4j;
import net.sf.json.JSONArray;
import org.apache.tomcat.util.http.fileupload.IOUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.view.freemarker.FreeMarkerConfigurer;
import org.w3c.dom.Document;
import org.xhtmlrenderer.pdf.ITextFontResolver;
import org.xhtmlrenderer.pdf.ITextRenderer;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import java.io.*;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.Map;

@SuppressWarnings("all")
@Slf4j
@Controller
@RequestMapping("file")
public class FileController {

    private static final String filename = "test.pdf";
    private static final String templatename = "test.ftl";

    @Autowired
    private FileProperties fileProperties;

    @Autowired
    private FreeMarkerConfigurer configurer;

    @GetMapping("previewFile")
    public void previewFile(HttpServletResponse response) {
        FileInputStream fis = null;
        ServletOutputStream os = null;
        try {
            fis = new FileInputStream(new File(fileProperties.getFilePath()));
            // response的设置必须在 拷贝流 之前
            response.setContentType("application/pdf");
            // 设置打开或者下载的方式
            response.addHeader("Content-Disposition", fileProperties.getWay() + ";filename*=" + URLEncoder.encode(fileProperties.getFileName(), "UTF-8"));
            os = response.getOutputStream();
            IOUtils.copy(fis, os);
            os.flush();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }finally {
            if (os != null) {
                try {
                    os.close();
                } catch (IOException e) {
                    throw new RuntimeException( "关闭流异常");
                }
            }
            if (fis != null) {
                try {
                    fis.close();
                } catch (IOException e) {
                    throw new RuntimeException("关闭流异常");
                }
            }
        }
    }

    @GetMapping("genPdf")
    public void genPdf() {
        HashMap<String, Object> map = new HashMap<>();
        OutputStream os = null;
        FileOutputStream fos = null;
        try {
            File file = new File(fileProperties.getStorePath());
            if (!file.exists()&&!file.isDirectory()) {
                file.mkdirs();
                log.info("创建文件夹成功!");
            }
            fos = new FileOutputStream(file.getPath() + File.separator + filename);

            ITextRenderer renderer = new ITextRenderer();
            Document doc = generateDoc(configurer, templatename, map);
            renderer.setDocument(doc, null);
            ITextFontResolver fontResolver = renderer.getFontResolver();
            fontResolver.addFont("simsun.ttc", BaseFont.IDENTITY_H, BaseFont.NOT_EMBEDDED);
            renderer.layout();
            renderer.createPDF(fos, false);
            renderer.finishPDF();

            fos.flush();
            System.out.println("生成PDF成功");

        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } catch (DocumentException e) {
            e.printStackTrace();
        } finally {
            try {
                if (os != null) {
                    os.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
            try {
                if (fos != null) {
                    fos.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    /**
     * 按模板和参数生成html字符串,再转换为flying-saucer识别的Document
     *
     * @param templateName freemarker模板名称
     * @param variables    freemarker模板参数
     * @return Document
     */
    private static Document generateDoc(FreeMarkerConfigurer configurer, String templateName,
                                        Map<String, Object> variables) {
        Template tp;
        try {
            configurer.getConfiguration().setDefaultEncoding("utf-8");
            tp = configurer.getConfiguration().getTemplate(templateName);
        } catch (IOException e) {
            log.error(e.getMessage(), e);
            return null;
        }

        StringWriter stringWriter = new StringWriter();
        try (BufferedWriter writer = new BufferedWriter(stringWriter)) {
            try {
                tp.process(variables, writer);
                writer.flush();
            } catch (TemplateException e) {
                log.error("模板不存在或者路径错误", e);
            } catch (IOException e) {
                log.error("IO异常", e);
            }
            DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
            factory.setFeature("http://apache.org/xml/features/disallow-doctype-decl", true);
            DocumentBuilder builder = factory.newDocumentBuilder();
            return builder.parse(new ByteArrayInputStream(stringWriter.toString().getBytes()));
        } catch (Exception e) {
            log.error(e.getMessage(), e);
            return null;
        }
    }

}
